/*
 * dsm_list.C
 *
 *  Created on: 28 nov. 2013
 *      Author: praaa
 */


#include <stdlib.h>
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#include <assert.h>
#include <string.h>
#include "dsm_list.h"

#define MAXBUF 1024


// On initialise les variables de la structure

t_machine new_machine(char * name_machine,int num_port,pid_t pid){

	t_machine machine_new = malloc(sizeof(t_machine));

	machine_new->machinename=malloc(MAXBUF*sizeof(char));

	machine_new->machinename=name_machine;

	machine_new->num_port=num_port;

	machine_new->pid=pid;

	int taille_machine=strlen(name_machine);

	machine_new->taille_machine=taille_machine;

	machine_new->next = NULL;

	return machine_new;
}


void set_next(t_machine machine_prev, t_machine machine_next){
	machine_prev->next = machine_next;
}



// On vérifie si la liste est vide

int is_empty(t_machine_list l){
	return (!(l->head_list));
}

// Initialisation de la liste
t_machine_list new_t_machine_list(){

	t_machine_list l = malloc(sizeof(struct t_machine_list));
	l->head_list = NULL;
	l->end_list = NULL;
	return l;
}

// On ajoute un nouveau machine à la liste

void add_t_machine_list(t_machine_list l, char * name_machine,int num_port,pid_t pid){
	assert(l);
	/* Definition of the added s_machine */

	t_machine machine_new = new_machine(name_machine,num_port,pid);

	/* Adding the new s_machine */

	if(l->end_list == NULL){ /* empty t_machine_list */
		l->end_list = machine_new;
		l->head_list = machine_new;
	}

	else{
		set_next(l->end_list, machine_new);
		l->end_list = machine_new;
	}
}


char* get_name(t_machine machine){
	assert(machine);
	return machine->machinename;
}

int get_length(t_machine machine){
	assert(machine);
	return machine->taille_machine;
}

int get_port(t_machine machine){
	assert(machine);
	return machine->num_port;
}

pid_t get_pid(t_machine machine){
	assert(machine);
	return machine->pid;
}

t_machine machine_from_end_list(t_machine_list list){
	return list->end_list;
}
t_machine machine_from_head_list(t_machine_list list){
	return list->head_list;
}

void list_display(t_machine_list list){
	assert(list);

	t_machine_list tmp = list;

	t_machine machine =machine_from_head_list(tmp);
	assert(machine);

	while(machine != NULL){

		int num_port=get_port(machine);
		int taille = get_length(machine);
		char * nom_machine;
		nom_machine=get_name(machine);
		pid_t pid=get_pid(machine);

		/*display*/

		fprintf(stdout,"-------------------\nList Machine ->%s \nnum_port: %d\nTaille= %d\nPid=%d\n--------------\n\n",nom_machine,num_port,taille,pid);

		machine=machine->next;
	}

}

t_machine find_machine_name(t_machine_list list, char * name){
	t_machine_list tmp=list;

	if (tmp != NULL){
		t_machine machine = machine_from_head_list(tmp);
		assert(machine);

		while( machine != NULL)
		{
			if( strcmp(get_name(machine),name) == 0){
				return machine;
			}
			machine=machine->next;
		}
	}

	return NULL;
}
